package public

import (
	"database/sql"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	gormDB *gorm.DB
	sqlDB  *sql.DB
)

type MySQLConf struct {
	DriverName      string `mapstructure:"driver_name"`
	DataSourceName  string `mapstructure:"data_source_name"`
	MaxOpenConn     int    `mapstructure:"max_open_conn"`
	MaxIdleConn     int    `mapstructure:"max_idle_conn"`
	MaxConnLifeTime int    `mapstructure:"max_conn_life_time"`
}

func InitDBPool() {
	//普通的db方式
	MysqlConfObj := &MySQLConf{}
	err := BaseConf.UnmarshalKey("mysql", MysqlConfObj)
	if err != nil {
		panic(err)
	}

	sqlDB, err = sql.Open("mysql", MysqlConfObj.DataSourceName)
	if err != nil {
		panic(err)
	}
	sqlDB.SetMaxOpenConns(MysqlConfObj.MaxOpenConn)
	sqlDB.SetMaxIdleConns(MysqlConfObj.MaxIdleConn)
	sqlDB.SetConnMaxLifetime(time.Duration(MysqlConfObj.MaxConnLifeTime) * time.Second)
	err = sqlDB.Ping()
	if err != nil {
		panic(err)
	}

	gormDB, err = gorm.Open(mysql.New(mysql.Config{
		Conn: sqlDB,
	}), &gorm.Config{})
	if err != nil {
		panic(err)
	}
}

func GetGormPool() *gorm.DB {
	return gormDB
}
func CloseDB() error {
	sqlDB.Close()
	return nil
}
